package main

import (
	"Ghost/mss"
	"container/list"
	"time"
)

var theMCMain *MainControl

func init() { theMCMain = mss.Install(CID_CONTROL, &MainControl{}).(*MainControl) }

type MainControl struct {
	mss.ControlHandle

	useds, frees *list.List
}

func (this *MainControl) HandleGore() *mss.Gore { return &mss.Gore{10, mss.DEF_CONTROL_CAPY} }

func (this *MainControl) HandleInit(own mss.IOControler) {
	this.ControlHandle.HandleInit(own)

	this.useds, this.frees = list.New(), list.New()

	this.TimerHandler(time.Second, this.onTimLaunchRobot)
}
func (this *MainControl) HandleTerm() { this.ControlHandle.HandleTerm() }

// -------- Logical
func (this *MainControl) CreateRobot(count int) {
	defer this.UnLock(this.Lock())
	for i := 0; i < count; i++ {
		theId := SID_ROBOT_BEGIN + this.useds.Len() + i
		if err := mss.Starta(mss.TSvieId(theId), &RobotClient{}); err != nil {
			break
		}
		this.useds.PushBack(theId)
	}
}
func (this *MainControl) DestryRobot(robotId int) {
	mss.Stop(mss.TSvieId(robotId), false, mss.ErrNormalExit)
}

func (this *MainControl) RecoverRobot(id mss.TSvieId) {
	defer this.UnLock(this.Lock())
	for e := this.useds.Front(); e != nil; e = e.Next() {
		if e.Value.(int) == int(id) {
			this.useds.Remove(e)
			this.frees.PushBack(int(id))
			break
		}
	}
}

// -------- Timer Handler
func (this *MainControl) onTimLaunchRobot(now time.Time) bool {
	defer this.UnLock(this.Lock())
	nCount := this.frees.Len()/100 + 1
	for n, e := 0, this.frees.Front(); e != nil && n < nCount; e, n = e.Next(), n+1 {
		mss.Starta(mss.TSvieId(e.Value.(int)), &RobotClient{})
	}
	return true
}
